package com.kitty.game.equip.service;


import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.config.NPC;
import com.kitty.game.drop.newservice.NewDropService;
import com.kitty.game.equip.model.ChargeData;
import com.kitty.game.equip.model.RoleData;
import com.kitty.game.newchoujiang.SendPopMessage;
import com.kitty.game.role.model.Role;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.DateUtils;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import com.kitty.common.utils.DecodeSendMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class NewChargeActivityService {
    private static String finalStartTime = "";
    private static String finalEndTime = "";
    private List<String> itemNameList = new ArrayList<>();
    @Autowired
    NewDropService newDropService;
    @Autowired
    RedisService redisService;
    @Autowired
    Dao dao;
    @Autowired
    ChatService chatService;
    public void queryChongZhiRangList(Role role,  NPC npc){
        String reward = "";
        for (int i = 0; i < 10; i++) {
            String r1 = DataCache.REDIS_DATA.get("chongzhi_rank_reward" + (i+1));
            if(StringUtils.isNotEmpty(r1)){
                String showName = "";
                for (String s : r1.split("\\+")) {
                    HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                    showName += stringObjectHashMap.get("showName").toString()+",";
                }
                if(showName.contains(",")){
                    showName = showName.substring(0,showName.length() -1);
                }
                reward += "  第"+(i+1)+"名：#R"+showName+"#n\n";
            }
        }
        String rankNames = "";
        List<String> choujiangrankList = redisService.getRankList("chongzhirank");
        for (int i = 0; i < 10; i++) {
            String s = "";
            int score = 0;
            try{
                s = choujiangrankList.get(i);
                score = redisService.findScore("chongzhirank", s);
            }catch(Exception e){
                s  = "虚位以待";
            }
            if("虚位以待".equals(s)){
                rankNames += "  第"+(i+1)+"名：#G"+s+"#n\n";
            }else{
                rankNames += "  第"+(i+1)+"名：#Y"+s+"#n    充值：#R "+score+"#n\n";
            }
        }
        String currentRank;
        int choujiangrank = redisService.find("chongzhirank", role.getName());
        if (choujiangrank == 0) {
            currentRank="# 当前没上榜，请道友再接再厉";
        } else {
            currentRank="# 当前排名：#R" +choujiangrank + "#n";
        }
        String state = redisService.get("chongzhi_rank_state").toString();
        String nowDate = "";
        if ("1".equals(state)) {
            nowDate = finalStartTime+"  -  "+finalEndTime;
        }else{
            nowDate = "未开始";
        }
        SendPopMessage respGeneralNotify = new SendPopMessage();
        String message = "CaseQingzkzRuleDlg|"+nowDate+"|"+rankNames+"|"+currentRank+"|"+reward;
        respGeneralNotify.setName(message);
        respGeneralNotify.setType((byte)2);
        MessagePusher.pushMessage(role, respGeneralNotify);

        //newNpcService.sendNpcContent(role, npc, getShow(role));
        return;
    }

    //增加充值
    public void addChongzhiRankCount(Role role, int money) {
        String state = redisService.get("chongzhi_rank_state").toString();
        if ("1".equals(state)) {
            String content = redisService.get("chongzhi_rank").toString();
            ChargeData chargeData = Json.fromJson(ChargeData.class, content);
            String curr = DateUtils.formatDate(new Date());
            RoleData roleData = new RoleData();
            if(chargeData.getHashMap() == null){
                chargeData.setHashMap(new HashMap<>());
            }
            if( chargeData.getHashMap().containsKey(role.getUid())){
                roleData = chargeData.getHashMap().get(role.getUid());
                roleData.setCharge(money + roleData.getCharge());
            }else{
                roleData.setCharge(money);
                roleData.setName(role.getName());
                roleData.setUid(role.getUid());
                chargeData.getHashMap().put(role.getUid(), roleData);
            }
            redisService.add("chongzhirank",role.getName(),(double)roleData.getCharge());
            String s = Json.toJson(chargeData);
            redisService.set("chongzhi_rank",s);
        }
    }
    public void notice(boolean boo) {
        String state =redisService.get("chongzhi_rank_state").toString();
        if (!"1".equals(state)) {
            return ;
        }
        StringBuilder notice = new StringBuilder("充值排行榜奖励将于23:50自动发放到背包,当前充值排行榜：");
        List<String> chongzhirankList = redisService.getRankList("chongzhirank");
        String[] strings = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十"};
        for (int i = 0; i < chongzhirankList.size(); i++) {
            if (i >= 10) {
                break;
            }
            int chongzhirank = redisService.findScore("chongzhirank", chongzhirankList.get(i));
            notice.append("第" + strings[i] + "名：#R" + chongzhirankList.get(i) + "#n 充值#R" + chongzhirank + " #n 奖励#R"+ itemNameList.get(i)+"#n ");
        }
        chatService.sendAdnotice(notice.toString());

    }

    //查看抽奖排行榜
    public String getShow(Role role) {
        String state = redisService.get("chongzhi_rank_state").toString();
        if (!"1".equals(state)) {
            return "当前没有充值排行榜活动 [离开]";
        }
        StringBuilder stringBuilder = new StringBuilder("充值排行榜奖励，活动结束自动发放。");
        int chongzhirank = redisService.find("chongzhirank", role.getName());
        if (chongzhirank == 0) {
            stringBuilder.append("#R当前没上榜，请道友再接再厉#n");
        } else {
            stringBuilder.append("当前第#R" +chongzhirank + "#n名");
        }
        stringBuilder.append("[离开]");
        return stringBuilder.toString();
    }







    private static final String NOTICE_CONTENT = "充值排行榜活动开始了，时间：%s-%s,活动结束后前十名将获得丰厚的奖励！";
        /*
        开启充值排行榜
     */
    public void startChongzhiank(String startTime,String endTime){
        finalStartTime = startTime;
        finalEndTime = endTime;
        redisService.set("chongzhi_rank_state","1");
        String notice = String.format(NOTICE_CONTENT, startTime,endTime);
        SpringUtils.getChatService().sendSystem(notice, Const.BRODCAST_MSG_TYPE_ROLE);
        //String choujiang_rank = redisService.get("choujiang_rank").toString();
        //重置抽奖次数记录信息
        ChargeData chargeData = new ChargeData();
        chargeData.setTime(System.currentTimeMillis());
        String chargeString = Json.toJson(chargeData);
        redisService.set("chongzhi_rank",chargeString);
        //清空排行榜信息
        redisService.delAllRank("chongzhirank");

        for (int i = 0; i < 10; i++) {
            String r1 = DataCache.REDIS_DATA.get("chongzhi_rank_reward" + (i+1));
            if(StringUtils.isNotEmpty(r1)){
                String showName = "";
                for (String s : r1.split("\\+")) {
                    HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                    showName += stringObjectHashMap.get("showName").toString()+",";
                }
                if(showName.contains(",")){
                    showName = showName.substring(0,showName.length() -1);
                }
                itemNameList.add(showName);
            }
        }
    }
    public void rebootChongzhiRank(String startTime,String endTime){
        finalStartTime = startTime;
        finalEndTime = endTime;

        for (int i = 0; i < 10; i++) {
            String r1 = DataCache.REDIS_DATA.get("chongzhi_rank_reward" + (i+1));
            if(StringUtils.isNotEmpty(r1)){
                String showName = "";
                for (String s : r1.split("\\+")) {
                    HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                    showName += stringObjectHashMap.get("showName").toString()+",";
                }
                if(showName.contains(",")){
                    showName = showName.substring(0,showName.length() -1);
                }
                itemNameList.add(showName);
            }
        }
    }
    /*
   关闭抽奖排行榜
    */
    public void endChongZhiRank(){
        log.info("充值排行榜结束，正在结算奖励。");
        String state = redisService.get("chongzhi_rank_state");
        if("1".equals(state)){
            redisService.set("chongzhi_rank_state","0");
            //发送奖励
            try{
                sendChongZhiRankReward();
            }catch(Exception e){
                log.info("发送充值排行榜奖励出错：",e);
            }finally {
                ChargeData chargeData = new ChargeData();
                chargeData.setTime(System.currentTimeMillis());
                String s = Json.toJson(chargeData);
                redisService.set("chongzhi_rank",s);
                //清空排行榜信息
                redisService.delAllRank("chongzhirank");
            }
        }
    }

    //抽奖排行榜结算奖励
    public void sendChongZhiRankReward(){
        List<String> names = redisService.getRankList("chongzhirank");
        for (int i = 0; i < 10; i++) {
            if(names.size()>i){
                Role role = SpringUtils.getRoleService().getPlayerBy(names.get(i));
                String reward = DataCache.REDIS_DATA.get("chongzhi_rank_reward" + (i+1)).toString();
                if(StringUtils.isNotEmpty(reward)){
                    String showName = "";
                    for (String s : reward.split("\\+")) {
                        HashMap<String, Object> stringObjectHashMap = DecodeSendMessage.buildSendRewardMessage(s);
                        showName += stringObjectHashMap.get("showName").toString()+",";
                        newDropService.addRewardTask(role,s,"");
                    }
                    if(showName.contains(",")){
                        showName = showName.substring(0,showName.length() -1);
                    }
                    String msg = "恭喜#Y" + role.getName() + "#n在充值排行榜活动中获得第#R" + (i+1) +"#n名，获得#Y"+showName+"#n奖励！";
                    SpringUtils.getChatService().sendAdnotice(msg);
                }
            }
        }
    }
}